import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authAPI } from '@/api/auth'
import { ElMessage } from 'element-plus'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))

  const isAuthenticated = computed(() => !!token.value)

  const login = async (data: { username: string; password: string }) => {
    try {
      const res = await authAPI.login(data)
      token.value = res.token
      userInfo.value = {
        username: res.username,
        userId: res.userId,
        email: res.email
      }
      localStorage.setItem('token', res.token)
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
      ElMessage.success('登录成功')
      return true
    } catch (error) {
      console.error('登录失败:', error)
      ElMessage.error('登录失败，请检查用户名和密码')
      return false
    }
  }

  const register = async (data: { username: string; password: string; email: string }) => {
    try {
      const res = await authAPI.register(data)
      ElMessage.success('注册成功')
      return res
    } catch (error) {
      ElMessage.error('注册失败')
      throw error
    }
  }

  const logout = () => {
    token.value = ''
    userInfo.value = {}
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    ElMessage.success('已退出登录')
  }

  return {
    token,
    userInfo,
    isAuthenticated,
    login,
    logout,
    register
  }
})
